package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client; //es客户端
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * ES条件搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.入参校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.创建request对象
        SearchRequest request = new SearchRequest("app_info_article");
        //3.构建DSL
        //构建boolquery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字查询
        boolQueryBuilder.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));

        //查询小于mindate数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));

        request.source().query(boolQueryBuilder);
        //分页
        request.source().from(0);
        request.source().size(dto.getPageSize());
        //倒序
        request.source().sort("publishTime", SortOrder.DESC);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        request.source().highlighter(highlightBuilder);
        SearchResponse searchResponse = null;

        try {
            //4.发送请求
            searchResponse = client.search(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("发送es检索异常:" + e);
        }

        //5.解析结果
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<Map> resList = new ArrayList<>();

        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() > 0) {
                Text[] titles = highlightFields.get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title", title);
            } else {
                //原始标题
                map.put("h_title", map.get("title"));
            }
            resList.add(map);
        }

        ///异步调用保存搜索关键词记录功能
        //当前登录用户不为空,且在首页搜索 (输入关键词后,如果翻到第二页,无需再次保存当前这个搜索关键词了) , 才进行搜索关键词记录保存
        if (ApUserThreadLocalUtil.getUser().getId() != null && dto.getFromIndex() == 0) {
            apUserSearchService.insert(dto.getSearchWords(), ApUserThreadLocalUtil.getUser().getId());
        }

        return ResponseResult.okResult(resList);
    }
}
